package controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import pojo.UserForm;
import service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Log logger = LogFactory.getLog(UserController.class);
    @Autowired
    public UserService userService;

    @PostMapping("/doLogin")
    public String login(UserForm user, HttpSession session, Model model){
        if(userService.login(user)){
            session.setAttribute("u",user);
            logger.info("login success");
            model.addAttribute("messageCorrect", "登录成功");
            return "main";
        }else {
            logger.info("login fail");
            model.addAttribute("messageError", "用户名或密码错误");
            return "login";
        }
    }

    @PostMapping("/doRegister")
    public String register(UserForm user, Model model){
        if(userService.register(user)){
            logger.info("register success");
            model.addAttribute("messageCorrect", "注册成功,请登录");
            return "login";
        }else {
            logger.info("register fail");
            model.addAttribute("uname", user.getUname());
            model.addAttribute("messageError", "2次输入的密码不一致或用户已存在");
            return "register";
        }
    }
}
